import 'package:flutter/material.dart';

import 'package:get/get.dart';
import '../../data/models/prompt_model.dart';
import 'detail_logic.dart';
import 'detail_state.dart';

/// 详情页面视图 - Detail Page View
/// 显示 Prompt 的详细信息，包括内容展示、操作工具栏、版本信息等
class DetailPage extends StatelessWidget {
  const DetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(DetailLogic());
    final state = Get.find<DetailLogic>().state;

    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: _buildAppBar(logic, state),
      body: _buildBody(logic, state),
      floatingActionButton: _buildFloatingActionButton(logic, state),
    );
  }

  /// 构建应用栏 - Build App Bar
  PreferredSizeWidget _buildAppBar(DetailLogic logic, DetailState state) {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.white,
      foregroundColor: Colors.black87,
      title: Obx(() => Text(
        state.prompt.value?.title ?? '详情',
        style: const TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w600,
        ),
      )),
      actions: [
        // 收藏按钮 - Favorite Button
        Obx(() => IconButton(
          icon: Icon(
            state.prompt.value?.getIsFavorite() == true
              ? Icons.favorite
              : Icons.favorite_border,
          color: state.prompt.value?.getIsFavorite() == true 
                ? Colors.red 
                : Colors.grey[600],
          ),
          onPressed: logic.toggleFavorite,
          tooltip: '收藏',
        )),
        
        // 分享按钮 - Share Button
        IconButton(
          icon: Icon(Icons.share, color: Colors.grey[600]),
          onPressed: logic.sharePrompt,
          tooltip: '分享',
        ),
        
        // 更多操作 - More Actions
        PopupMenuButton<String>(
          icon: Icon(Icons.more_vert, color: Colors.grey[600]),
          onSelected: logic.handleMenuAction,
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: ListTile(
                leading: Icon(Icons.edit, size: 20),
                title: Text('编辑'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'duplicate',
              child: ListTile(
                leading: Icon(Icons.copy, size: 20),
                title: Text('复制'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'export',
              child: ListTile(
                leading: Icon(Icons.download, size: 20),
                title: Text('导出'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'versions',
              child: ListTile(
                leading: Icon(Icons.history, size: 20),
                title: Text('版本历史'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: ListTile(
                leading: Icon(Icons.delete, size: 20, color: Colors.red),
                title: Text('删除', style: TextStyle(color: Colors.red)),
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建主体内容 - Build Body Content
  Widget _buildBody(DetailLogic logic, DetailState state) {
    return Obx(() {
      if (state.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }

      if (state.prompt.value == null) {
        return _buildErrorState();
      }

      return SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 基本信息卡片 - Basic Info Card
            _buildBasicInfoCard(logic, state),
            const SizedBox(height: 16),
            
            // 内容卡片 - Content Card
            _buildContentCard(logic, state),
            const SizedBox(height: 16),
            
            // 模板变量卡片 - Template Variables Card
            if (state.prompt.value!.getHasTemplateVariables())
              _buildTemplateVariablesCard(logic, state),
            
            if (state.prompt.value!.getHasTemplateVariables())
              const SizedBox(height: 16),
            
            // 统计信息卡片 - Statistics Card
            _buildStatisticsCard(logic, state),
            const SizedBox(height: 16),
            
            // 版本信息卡片 - Version Info Card
            _buildVersionInfoCard(logic, state),
            const SizedBox(height: 80), // 为浮动按钮留出空间
          ],
        ),
      );
    });
  }

  /// 构建错误状态 - Build Error State
  Widget _buildErrorState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '无法加载 Prompt 详情',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () => Get.back(),
            child: const Text('返回'),
          ),
        ],
      ),
    );
  }

  /// 构建基本信息卡片 - Build Basic Info Card
  Widget _buildBasicInfoCard(DetailLogic logic, DetailState state) {
    final prompt = state.prompt.value!;
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题和描述 - Title and Description
            Text(
              prompt.title,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            
            if (prompt.description.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                prompt.description,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                  height: 1.4,
                ),
              ),
            ],
            
            const SizedBox(height: 16),
            
            // 标签和分类 - Tags and Category
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                // 分类标签 - Category Tag
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.blue[100],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.category, size: 14, color: Colors.blue[700]),
                      const SizedBox(width: 4),
                      Text(
                        prompt.category,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.blue[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 格式标签 - Format Tag
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.green[100],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.description, size: 14, color: Colors.green[700]),
                      const SizedBox(width: 4),
                      Text(
                        prompt.getFormat().toUpperCase(),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.green[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 用户标签 - User Tags
                ...prompt.tags.map((tag) => Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    tag,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[700],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                )),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建内容卡片 - Build Content Card
  Widget _buildContentCard(DetailLogic logic, DetailState state) {
    final prompt = state.prompt.value!;
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 卡片标题 - Card Title
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.article, size: 20, color: Colors.blue),
                const SizedBox(width: 8),
                const Text(
                  'Prompt 内容',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                
                // 复制按钮 - Copy Button
                IconButton(
                  icon: const Icon(Icons.copy, size: 18),
                  onPressed: () => logic.copyContent(),
                  tooltip: '复制内容',
                ),
                
                // 预览/编辑切换 - Preview/Edit Toggle
                Obx(() => IconButton(
                  icon: Icon(
                    state.isPreviewMode.value ? Icons.edit : Icons.visibility,
                    size: 18,
                  ),
                  onPressed: logic.togglePreviewMode,
                  tooltip: state.isPreviewMode.value ? '编辑模式' : '预览模式',
                )),
              ],
            ),
          ),
          
          const Divider(height: 1),
          
          // 内容区域 - Content Area
          Obx(() => Container(
            width: double.infinity,
            constraints: const BoxConstraints(minHeight: 200),
            padding: const EdgeInsets.all(16),
            child: state.isPreviewMode.value
                ? _buildPreviewContent(prompt.content)
                : _buildRawContent(prompt.content),
          )),
        ],
      ),
    );
  }

  /// 构建预览内容 - Build Preview Content
  Widget _buildPreviewContent(String content) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: SelectableText(
        content,
        style: const TextStyle(
          fontSize: 14,
          height: 1.6,
          color: Colors.black87,
        ),
      ),
    );
  }

  /// 构建原始内容 - Build Raw Content
  Widget _buildRawContent(String content) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(8),
      ),
      child: SelectableText(
        content,
        style: const TextStyle(
          fontSize: 13,
          height: 1.5,
          color: Colors.white,
          fontFamily: 'monospace',
        ),
      ),
    );
  }

  /// 构建模板变量卡片 - Build Template Variables Card
  Widget _buildTemplateVariablesCard(DetailLogic logic, DetailState state) {
    final prompt = state.prompt.value!;
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 卡片标题 - Card Title
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.code, size: 20, color: Colors.orange),
                const SizedBox(width: 8),
                const Text(
                  '模板变量',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                Text(
                  '${prompt.templateVariables.length} 个变量',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          
          const Divider(height: 1),
          
          // 变量列表 - Variables List
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: prompt.templateVariables.length,
            separatorBuilder: (context, index) => const Divider(height: 1),
            itemBuilder: (context, index) {
              final variable = prompt.templateVariables[index];
              return ListTile(
                leading: Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color: variable.isRequired ? Colors.red[100] : Colors.grey[200],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    variable.isRequired ? Icons.star : Icons.code,
                    size: 16,
                    color: variable.isRequired ? Colors.red[700] : Colors.grey[600],
                  ),
                ),
                title: Text(
                  '{{${variable.name}}}',
                  style: const TextStyle(
                    fontFamily: 'monospace',
                    fontWeight: FontWeight.w500,
                  ),
                ),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (variable.description.isNotEmpty)
                      Text(variable.description),
                    if (variable.defaultValue.isNotEmpty)
                      Text(
                        '默认值: ${variable.defaultValue}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                  ],
                ),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (variable.isRequired)
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.red[100],
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          '必需',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.red[700],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    const SizedBox(width: 8),
                    Text(
                      variable.type,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  /// 构建统计信息卡片 - Build Statistics Card
  Widget _buildStatisticsCard(DetailLogic logic, DetailState state) {
    final prompt = state.prompt.value!;
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 卡片标题 - Card Title
            const Row(
              children: [
                Icon(Icons.analytics, size: 20, color: Colors.purple),
                SizedBox(width: 8),
                Text(
                  '统计信息',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 16),
            
            // 统计数据网格 - Statistics Grid
            GridView.count(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              crossAxisCount: 2,
              childAspectRatio: 3,
              crossAxisSpacing: 16,
              mainAxisSpacing: 12,
              children: [
                _buildStatItem('字符数', '${prompt.getContentLength()}', Icons.text_fields),
                _buildStatItem('单词数', '${prompt.getWordCount()}', Icons.format_quote),
                _buildStatItem('行数', '${prompt.getLineCount()}', Icons.format_list_numbered),
                _buildStatItem('使用次数', '${prompt.usageCount}', Icons.play_arrow),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建统计项 - Build Stat Item
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Icon(icon, size: 16, color: Colors.grey[600]),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建版本信息卡片 - Build Version Info Card
  Widget _buildVersionInfoCard(DetailLogic logic, DetailState state) {
    final prompt = state.prompt.value!;
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 卡片标题 - Card Title
            Row(
              children: [
                const Icon(Icons.history, size: 20, color: Colors.teal),
                const SizedBox(width: 8),
                const Text(
                  '版本信息',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                TextButton(
                  onPressed: logic.viewVersionHistory,
                  child: const Text('查看历史'),
                ),
              ],
            ),
            
            const SizedBox(height: 16),
            
            // 版本详情 - Version Details
            Row(
              children: [
                Expanded(
                  child: _buildVersionDetailItem(
                    '当前版本',
                    prompt.version.toString(),
                    Icons.tag,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildVersionDetailItem(
                    '创建时间',
                    _formatDate(prompt.createdAt),
                    Icons.access_time,
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 12),
            
            Row(
              children: [
                Expanded(
                  child: _buildVersionDetailItem(
                    '最后更新',
                    _formatDate(prompt.getUpdatedAt()),
                    Icons.update,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Obx(() => _buildVersionDetailItem(
                    '版本数量',
                    '${state.getVersionCount()}',
                    Icons.layers,
                  )),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建版本详情项 - Build Version Detail Item
  Widget _buildVersionDetailItem(String label, String value, IconData icon) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, size: 14, color: Colors.grey[600]),
              const SizedBox(width: 6),
              Text(
                label,
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建浮动操作按钮 - Build Floating Action Button
  Widget _buildFloatingActionButton(DetailLogic logic, DetailState state) {
    return Obx(() => FloatingActionButton.extended(
      onPressed: state.prompt.value != null ? logic.usePrompt : null,
      icon: const Icon(Icons.play_arrow),
      label: const Text('使用 Prompt'),
      backgroundColor: Colors.blue,
      foregroundColor: Colors.white,
    ));
  }

  /// 格式化日期 - Format Date
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);
    
    if (difference.inDays > 0) {
      return '${difference.inDays} 天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} 小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} 分钟前';
    } else {
      return '刚刚';
    }
  }
}